package com.miracle.mango.entity.user;

import com.miracle.mango.util.ServiceException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.util.UUID;

/**
 * @description:
 * @author: wangxf
 * @date: Created in 2020/8/22 23:33
 */
@Service
@Validated
public class UserServive {

    @Autowired
    private UserMapper userMapper;

    public int save(@Valid User user) {
        if(StringUtils.isEmpty(user.getId())) {
            user.setId(UUID.randomUUID().toString());
        }
        return userMapper.save(user);
    }

    public int savePermission(String userId, String roleId) {
        String id = UUID.randomUUID().toString();
        return userMapper.saveRole(id, userId, roleId);
    }

    public int update(User user) {
        User saved = userMapper.getById(user.getId());
        if (null == saved) {
            throw new ServiceException("用户信息不存在!");
        }
        BeanUtils.copyProperties(user, saved);
        return userMapper.update(user);
    }

    public int removeById(String id) {
        return userMapper.removeById(id);
    }

}
